import { useRef, useState } from "react";
import styles from "./index.module.less";
import {
	ProForm,
	ProFormInstance,
	ProFormText,
	ProFormTextArea,
	ProFormSelect,
} from "@ant-design/pro-components";
import { Affix, Button, ConfigProvider, Flex, Space, message } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { createDock, updateDock, getDockDetail } from "@/api/modules/platform";
import { getDockTypeDict } from "@/api/modules/dict";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import dayjs from "dayjs";
import AMap from "@/components/AMap";
import { map, forEach } from 'lodash';
import { isValidLngLatArray } from "@/utils/utils";
import { PageContainer } from '@ant-design/pro-layout';

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const [detailInfo, setDetailInfo] = useState(null);
	const [points, setPoints] = useState<any[]>([]);

	const { loading: loadingDetail, runAsync: getDetailAsync, data: walkDetailInfo } = useRequest(getDockDetail, { manual: true });

	useEffect(() => {
		if (!detailId) return;
		getDetailAsync({ id: detailId }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data?.scene ?? {};
				setDetailInfo(data);
				handleChangeRange(data?.points);
				const InitialData = {
					...data,
				};
				formRef.current?.setFieldsValue(InitialData);
			}
		});
	}, []);

	//获取月台类型
	const handleGetTypeList = async () => {
		const res: any = await getDockTypeDict({ parentId: 0, code: "AREA_TYPE" })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data
		}
	}

	const handleValuesChange = (changeValue: any) => {
		if ('points' in changeValue) {
			const result = changeValue.points
			handleChangeRange(result);
		}
	};

	const handleSubmit = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		// const pointList = map(values.points ? values.points.split(';') : [], (item: any) => {
		// 	const positionArr = item ? item.split(',') : [];
		// 	return positionArr;
		// })
		const requestData = {
			...values,
			coordinate: "WGS84",
		};
		const callback = () => {
			if (detailId) {
				updateDock({ ...requestData, id: detailId }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("更新成功");
						handleBack();
					}
				});
			} else {
				createDock({ ...requestData }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			}
		};
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleChangeRange = async (result: any) => {
		handleCheckRangeFormat(result).then(() => {
			// const result = '120.665379,31.127306;120.667772,31.127554;120.667814,31.123026;120.665336,31.123054;120.665379,31.127306'
			let rangeList = []
			try {
				rangeList = JSON.parse(result);
			} catch (error) {
				return Promise.reject('经纬度格式不正确');
			}
			setPoints([{ path: rangeList }])
		});
	}

	const handleCheckRangeFormat = (value: any) => {
		// const rangeList = value ? value.split(';') : [];
		let rangeList = []
		try {
			rangeList = JSON.parse(value);
			if(!isValidLngLatArray(rangeList)) {
				return Promise.reject('请确保范围区域是由经纬组成的二维数组');
			}
		} catch (error) {
			return Promise.reject('经纬度格式不正确');
		}
		if (rangeList.length < 3) {
			return Promise.reject('感知范围最少需要三个点');
		} else {
			let errorKeywordArr = [];
			forEach(rangeList, (item: any) => {
				if (item.length !== 2) {
					errorKeywordArr.push(item);
				}
			})
			if (errorKeywordArr.length > 0) {
				return Promise.reject('经纬度格式不正确');
			} else {
				return Promise.resolve();
			}
		}
	}

	const handleBack = () => {
		navigate("/platform/dock");
	};

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: '/platform/dock', breadcrumbName: '月台管理' },
					{ href: '', breadcrumbName: detailId ? '编辑月台' : '新增月台' },
				],
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.detailContainer}>
					<div className={styles.container}>
						<ProForm
							colon={false}
							submitter={false}
							formRef={formRef}
							layout="horizontal"
							onValuesChange={handleValuesChange}
							labelCol={{ span: 6 }}
						>
							<div className={styles.content_wrap}>
								<div className={styles.content}>
									<div className={styles.moduleTitle}>{detailId ? "修改区域" : "新增区域"}</div>
									<ProFormText
										label="月台名称"
										name="scName"
										rules={[
											{ required: true, message: "请输入月台名称" },
										]}
									/>
									<ProFormSelect
										label="月台类型"
										name="type"
										rules={[{ required: true, message: "请选择月台类型" }]}
										placeholder={"请选择月台类型"}
										request={handleGetTypeList}
										fieldProps={{
											fieldNames: {
												label: 'label',  // 显示文本对应的字段
												value: 'value',    // 值对应的字段
											}
										}}
									/>
									<ProFormTextArea
										label="范围区域"
										name="points"
										rules={[
											{ required: true, message: "请输入范围区域" },
											{ validator: (_, value) => handleCheckRangeFormat(value) }
										]}
										placeholder={"请输入范围区域"}
										fieldProps={{
											rows: 14,
											style: { resize: 'none' },
											// onBlur: handleChangeRange
										}}
									/>
								</div>
							</div>
						</ProForm>
						<Flex justify="right" className={styles.btns}>
							<Space size={10}>
								<Button ghost type="primary" onClick={() => navigate(-1)}>
									返回
								</Button>
								<Button type="primary" onClick={handleSubmit}>
									保存
								</Button>
							</Space>
						</Flex>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap polygons={points} />
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
